<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'

import { useUserAddOrEdit, useUserInfo } from '@fl/api/iam-api/user-manage'
import { SubmitBtn } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import { isPhone } from '@fl/utils/validate'

const props = withDefaults(defineProps<{
    treeData: any
    roleOptions: any
}>(), {
    treeData: [],
    roleOptions: []
})
const { treeData, roleOptions } = toRefs(props)


const visible = defineModel<boolean>('visible', { required: true })
const id = defineModel<string>('id', { required: true })

const formRef = ref()
const title = ref<string>('添加用户')

type RequestIndex = {
    deptId?: any
    email?: string
    nickName?: string
    password?: string
    phonenumber?: string
    remark?: string
    roleIds?: Array<number>
    sex?: string
    status?: string
    userName?: string
}

const initialState = {
    deptId: [],
    email: '',
    nickName: '',
    password: '123456',
    phonenumber: '',
    remark: '',
    roleIds: [],
    sex: '',
    status: '0',
    userName: '',
}
const state = ref<RequestIndex>(cloneDeep(initialState))

// 详情
const { data: detail, isLoading } = useUserInfo(id)
watchEffect(() => {
    if (detail.value) {
        title.value = '编辑用户'
        state.value = cloneDeep(detail.value.user)
        state.value.password = '******'
        state.value.roleIds = detail.value.roleIds
    }
})

// 提交表单
const { isPending, mutate } = useUserAddOrEdit()

// 提交
async function submit() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        const arr = toRaw(state.value.deptId)
        const params = {
            id: id.value ?? '',
            ...unref(state),
            deptId: arr?.length > 0 ? arr[arr.length - 1] : '',
            password: id.value ? '' : state.value.password, // 密码编辑时传 ''
        }
        // console.log('params', params)
        mutate(params, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                cancel()
            },
        })
    }
}

function cancel() {
    reset()
}

function reset() {
    visible.value = false
    id.value = ''
    state.value = cloneDeep(initialState)
    formRef.value.formInstance.resetFields()
}

const columns = computed<PlusColumn[]>(() => {
    return [
        {
            colProps: {
                span: 12,
            },
            fieldProps: {
                maxlength: 10,
            },
            label: '用户昵称',
            prop: 'nickName',
        },
        {
            colProps: {
                span: 12,
            },
            label: '归属部门',
            prop: 'deptId',
        },
        {
            colProps: {
                span: 12,
            },
            fieldProps: {
                maxlength: 11,
            },
            label: '手机号码',
            prop: 'phonenumber',
        },
        {
            colProps: {
                span: 12,
            },
            label: '邮箱',
            prop: 'email',
        },
        {
            colProps: {
                span: 12,
            },
            fieldProps: computed(() => ({
                disabled: !!id.value,
                maxlength: 10,
            })),
            label: '登录名',
            prop: 'userName',
        },
        {
            colProps: {
                span: 12,
            },
            fieldProps: computed(() => ({
                disabled: !!id.value,
                maxlength: 20,
            })),
            label: '用户密码',
            prop: 'password',
        },
        {
            colProps: {
                span: 12,
            },
            label: '用户性别',
            options: [
                {
                    label: '男',
                    value: '0',
                },
                {
                    label: '女',
                    value: '1',
                },
                {
                    label: '未知',
                    value: '2',
                },
            ],
            prop: 'sex',
            valueType: 'select',
        },
        {
            colProps: {
                span: 12,
            },
            label: '状态',
            prop: 'status',
        },
        {
            colProps: {
                span: 12,
            },
            fieldProps: {
                filterable: true,
                multiple: true,
            },
            label: '角色',
            options: computed(() => {
                return roleOptions.value
            }),
            prop: 'roleIds',
            valueType: 'select',
        },
        {
            label: '备注',
            prop: 'remark',
            // valueType
        },
    ]
})
const validatorphonenumber = (rule, value, callback) => {
    if (!isPhone(value))
        callback(new Error('请输入正确的手机号'))
    else callback()
}
const reg = /^[a-zA-Z0-9]+$/
const validatorpassword = (rule, value, callback) => {
    // 编辑忽略密码校验
    if(reg.test(value) || !!id.value) {
        callback()
    } else {
        callback(new Error('请输入数字和英文'))
    }
        
}
const rules = {
    nickName: [
        {
            message: '请输入用户昵称',
            required: true,
        },
    ],
    password: [
        {
            message: '请输入数字和英文',
            required: true,
            trigger: 'blur',
            validator: validatorpassword
        },
    ],
    userName: [
        {
            message: '请输入登录名',
            required: true,
        },
    ],
    roleIds: [
        {
            message: '请选择角色',
            required: true,
        },
    ],
    phonenumber: [
        {
            message: '请输入正确的手机号',
            required: true,
            trigger: 'blur',
            validator: validatorphonenumber
        },
    ],
}
</script>

<template>
    <PlusDialog v-model="visible"
                :title="title"
                width="800"
                close-on-press-escape
                :has-footer="false"
                @cancel="cancel"
                @closed="reset"
    >
        <ElSkeleton v-if="isLoading"
                    animated
                    class="mt-20"
        />

        <template v-else>
            <div class="mt-20">
                <PlusForm ref="formRef"
                          v-model="state"
                          :columns="columns"
                          :label-width="100"
                          :rules="rules"
                          :has-footer="false"
                          :row-props="{ gutter: 20 }"
                >
                    <template #plus-field-deptId>
                        <el-cascader v-model="state.deptId"
                                     :options="treeData"
                                     :props="{ label: 'label', value: 'id', checkStrictly: true }"
                                     :show-all-levels="false"
                                     style="width:100%;"
                        />
                    </template>

                    <template #plus-field-status>
                        <el-radio-group v-model="state.status">
                            <el-radio label="正常"
                                      value="0"
                            />

                            <el-radio label="停用"
                                      value="1"
                            />
                        </el-radio-group>
                    </template>
                </plusform>
            </div>

            <div class="mx-auto mt20 flex justify-center">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="isPending"
                           @click="submit"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>

<style lang="scss" scoped></style>
